package testGroovy


import static groovyx.net.http.ContentType.BINARY
import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

import org.cyberneko.html.parsers.SAXParser

class TestHttpClient {

	private static final _URL_PROPOSAL = 'ebusiness/auto/newness/index.do'
	static main(args) {
		RESTClient client = new RESTClient('http://www.pingan.com/').with {
			client.params.setParameter(
					org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY ,
					new org.apache.http.HttpHost("127.0.0.1", 8888)
					)
			it
		}
		def params = [
			requestContentType  : URLENC,
			contentType         : BINARY,
			path                : _URL_PROPOSAL,
//			query 				: [
//				cityCode		:110100,
//				provinceCode	:110000
//				]
		]
		def nekoParser = new SAXParser().with {
			it.setFeature 'http://xml.org/sax/features/namespaces', false
			it
		}
		def htmlParser = new XmlParser(nekoParser)
		
//		def checkCodeFlag = client.get params, { resp, stream ->
////			((HttpResponseDecorator)resp).status
//			htmlParser.parse(stream).depthFirst().INPUT.find { it ->
//				'checkCodeName' == it.@id 
//			}
//			def flag = false
//			for (input in inputs) {
//				if(input.@id == 'checkCodeName') {
//					flag = true
//				}
//			}
//			flag
//		}
//		println checkCodeFlag
		
		client.get params, { resp, stream ->
			def imgSrc = htmlParser.parse(stream).depthFirst().IMG.find { 'yzm_img' == it.@class }.@src as String
			('E:/tmp.png' as File).withOutputStream { os ->
				os << new ByteArrayInputStream(Base64.decoder.decode(imgSrc.substring(22))) //前缀固定为data:image/gif;base64,
			}
		}
		def file = 'E:/tmp.png' as File
		
		if(file.exists()) {
			println '文件存在'
		}


		// 获取flowId
//		def flowid = client.get params, { resp, stream ->
//			htmlParser.parse(stream).depthFirst().DIV.find {
//				'main' == it.@id
//            }.@flowid
//		}
//
//		println flowid
	}

}
